package com.cyq.dascma.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyq.dascma.constant.ValidaEnum;
import com.cyq.dascma.dto.StudentInfoDto;
import com.cyq.dascma.entity.Student;
import com.cyq.dascma.entity.Teacher;
import com.cyq.dascma.exception.ServiceException;
import com.cyq.dascma.handler.valida.impl.StudentValidaImpl;
import com.cyq.dascma.result.Result;
import com.cyq.dascma.result.ResultGenerator;
import com.cyq.dascma.service.StudentService;
import com.cyq.dascma.util.RequestUtil;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * dingwen
 * 2021/3/9 17:35
 **/
@Api(tags = "学生模块")
@RestController
@RequestMapping("/student")
public class StudentController {

    private final StudentService studentService;

    @Autowired
    StudentController(StudentService studentService) {
        this.studentService = studentService;
    }


    /*
     * 查询所有学生列表
     * @param []
     * @return com.cyq.dascma.result.Result
     */
    @ApiOperation(value = "查询所有学生列表")
    @GetMapping("/list")
    public Result get() {
        List<Student> studentList = studentService.list();
        return ResultGenerator.genOkResult(studentList);
    }


    /*
     *查询所有学生信息列表  info
     * @param []
     * @return com.cyq.dascma.result.Result
     */
    @ApiOperation(value = "分页查询所有学生信息列表  info")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "studentId", value = "学号", required = false),
            @ApiImplicitParam(name = "studentName", value = "学生姓名", required = false),
            @ApiImplicitParam(name = "clazzName", value = "班级名称", required = false),
            @ApiImplicitParam(name = "clazzId", value = "班级编号", required = false),
            @ApiImplicitParam(name = "pageSize", value = "每页多少条", required = true),
            @ApiImplicitParam(name = "pageNum", value = "第几页", required = true),
    })

    @GetMapping("info/page")
    public Result get(@RequestParam(value = "studentId", required = false) String studentId,
                      @RequestParam(value = "studentName", required = false) String studentName,
                      @RequestParam(value = "clazzName", required = false) String clazzName,
                      @RequestParam(value = "clazzId", required = false) String clazzId,
                      @RequestParam(value = "pageSize") Integer pageSize,
                      @RequestParam("pageNum") Integer pageNum, HttpServletRequest request) {
        Map<String, Object> params = RequestUtil.getParameterMap(request);
        params.put("offset", ((pageNum - 1) * pageSize));
        params.put("limit", (pageSize));
        List<StudentInfoDto> studentInfoDtoList = studentService.findStudentInfoList(params);
        return ResultGenerator.genOkResult(studentInfoDtoList);
    }

    /*
     * 根据studentId修改学生信息
     * @param student
     * @return Result
     */
    @ApiOperation("根据studentId修改学生信息")
    @ApiImplicitParam(name = "student", value = "学生实体", required = true, dataType = "student", paramType = "body")
    @PutMapping("/modify")
    public Result modify(@RequestBody Student student) {
        try {
            new StudentValidaImpl().valida(ValidaEnum.MODIFY, student);
        } catch (ServiceException serviceException) {
            return serviceException.result();
        }
        boolean flag = studentService.updateById(student);
        return flag ? ResultGenerator.genOkResult("更新学生信息成功") : ResultGenerator.genFailureResult("更新学生信息失败");
    }

    /*
     * 学生用户登录
     * @param student
     * @return Result
     */
    @ApiOperation("学生用户登录")
    @ApiImplicitParam(name = "student", value = "学生实体", required = true, dataType = "student", paramType = "body")
    @PostMapping("/login")
    public Result login(@RequestBody Student student, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        try {
            new StudentValidaImpl().valida(ValidaEnum.LOGIN, student);
        } catch (ServiceException serviceException) {
            return serviceException.result();
        }
        QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
        studentQueryWrapper.and(wrapperById -> wrapperById.eq("student_id", student.getStudentId()))
                .and(wrapperByPassword -> wrapperByPassword.eq("student_password", student.getStudentPassword()));
        Student studentOne = studentService.getOne(studentQueryWrapper);
        request.getSession().setAttribute("user", studentOne);
        Cookie cookie = new Cookie("JSESSIONID", session.getId());
        cookie.setMaxAge(60 * 60);
        response.addCookie(cookie);
        return studentOne == null ? ResultGenerator.genFailureResult("登录失败") : ResultGenerator.genOkResult(studentOne);
    }

    /*
     * 根据学号删除学生信息
     * @param studentId
     * @return Result
     */
    @ApiOperation("根据学号删除学生信息")
    @ApiImplicitParam(name = "studentId", value = "学号", required = true, dataType = "String")
    @DeleteMapping("/remove/{studentId}")
    public Result remove(@PathVariable("studentId") String studentId) {
        boolean flag = studentService.removeById(studentId);
        return flag ? ResultGenerator.genOkResult("ok") : ResultGenerator.genFailureResult("删除失败");
    }

    /*
     *查询学生表总记录条数
     * @param []
     * @return com.cyq.dascma.result.Result
     */
    @ApiOperation("查询学生表总记录条数")
    @GetMapping("/total")
    public Result getTotal() {
        return ResultGenerator.genOkResult(studentService.count());
    }

    /*
     *退出登录
     * @param [request]
     * @return com.cyq.dascma.result.Result
     */
    @ApiOperation("退出登录")
    @GetMapping("/logout")
    public Result logout(HttpServletRequest request) {
        request.getSession().invalidate();
        return ResultGenerator.genOkResult("ok;");
    }


    /*
     *新增学生信息
     * @param [student]
     * @return com.cyq.dascma.result.Result
     */
    @ApiOperation("新增学生信息")
    @ApiImplicitParam(name = "student", value = "学生实体", required = true, dataType = "student", paramType = "body")
    @PostMapping("/add")
    public Result add(@RequestBody Student student) {
        try {
            new StudentValidaImpl().valida(ValidaEnum.ADD, student);
        } catch (ServiceException serviceException) {
            return serviceException.result();
        }
        // 默认密码为学号
        student.setStudentPassword(student.getStudentId());
        boolean flag = studentService.save(student);
        return flag ? ResultGenerator.genOkResult() : ResultGenerator.genFailureResult("新增学生失败");
    }

    /*
     *批量删除
     * @param [studentList]
     * @return com.cyq.dascma.result.Result
     */
    @ApiOperation("批量删除")
    @ApiImplicitParam(name = "studentList", value = "学生List", paramType = "body")
    @DeleteMapping("/remove/batch")
    public Result remove(@RequestBody List<Student> studentList) {
        List<String> ids = new ArrayList<>();
        studentList.stream().parallel().forEach(student -> ids.add(student.getStudentId()));
        boolean flag = studentService.removeByIds(ids);
        return flag ? ResultGenerator.genOkResult() : ResultGenerator.genFailureResult("批量删除失败");
    }


    /*
     *查询所有学生的ID & name 信息
     * @param []
     * @return com.cyq.dascma.result.Result
     */
    @ApiOperation("查询所有学生的ID & name 信息")
    @GetMapping("/ins")
    public Result getIns() {
        List<Student> studentList = studentService.list(new QueryWrapper<Student>().select("student_id", "student_name"));
        return ResultGenerator.genOkResult(studentList);
    }



}
